package com.to.controller;

import com.to.bean.User;
import com.to.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


@WebServlet("/user")
public class UserServlet  extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        String uri = req.getRequestURI();
        System.out.println("uri = " + uri);
        switch (method){
            case "lo  gin": login(req,resp); break; // 用户登陆
            case "show": show(req,resp); break; // 用户登陆
        }

    }

    private void show(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("show");
        // 获取所有用户信息,传递给show.jsp 页面
        UserService userService = new UserService();
        List<User> userList =  userService.selectAllUser();

        // 页面跳转, 选择作用域对象时考虑因素 1. 是否可以获取的到数据 2.内存的利用率
        req.setAttribute("ulist",userList);
        req.getRequestDispatcher("show.jsp").forward(req,resp);
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        // 获取前端传递的数据
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");

        // 将获取的数据交给业务逻辑层处理
        UserService us = new UserService();
        // 调用方法获取结果
        User user = us.getUserByNameAndPassword(username,pwd);

        // 控制页面的跳转
        if(user != null){// 表示的登陆成功
            HttpSession session=req.getSession();
            session.setAttribute("user",user);
            resp.sendRedirect("show?method=show");
        }else{ // 登陆失败
            req.setAttribute("mes", "用户名或者密码错误");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
